<template>
	<PageWrapper contentFullHeight fixedHeight :contentClass="'flex'">
		<BasicTable @register="registerTable">
			<template #beforeTable>
				<div class="pt-3 pb-3">
					<a-button class="mr-5" type="primary" @click="handleCreate">新增</a-button>
				</div>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.key == 'action'">
					<TableAction :divider="true" :actions="createActions(record)"></TableAction>
				</template>
			</template>
		</BasicTable>
		<AddOrEditModal @register="registerModal" @success="handleSuccess"></AddOrEditModal>
		<PermissionDrawer @register="registerDrawer" @success="handleSuccess"></PermissionDrawer>
	</PageWrapper>
</template>

<script setup lang="ts">
import { PageWrapper, BasicTable, TableAction } from '#/components';
import { useModal, useTable, useDrawer } from '#/hooks';
import { getRoleList, deleteRole } from '@/api/sys/role';
import type { ActionItem } from '#/types';
import AddOrEditModal from './components/AddOrEditItem.vue';
import PermissionDrawer from './components/Permission.vue';
import { useMessage } from '@/hooks/web/useMessage';

const columns = [
	{
		title: '角色名称',
		dataIndex: 'roleName',
	},
	{
		title: '角色编码',
		dataIndex: 'roleCode',
	},
	{
		title: '备注',
		dataIndex: 'remark',
	},
];

const [registerTable, { reload }] = useTable({
	columns,
	rowKey: 'roleId',
	api: getRoleList,
	useSearchForm: true,
	formConfig: {
		baseColProps: { span: 6 },
		schemas: [
			{
				field: 'roleName',
				label: '角色名称',
				component: 'Input',
			},
		],
	},
	actionColumn: {
		title: '操作',
		key: 'action',
		dataIndex: 'action',
		width: 240,
	},
});

const [registerModal, { openModal }] = useModal();

const { createMessage } = useMessage();

function createActions(record: Recordable): ActionItem[] {
	return [
		{
			title: '编辑',
			onClick: handleEdit.bind(null, record),
			disabled: record.username == 'admin',
		},
		{
			title: '权限',
			onClick: handlePermission.bind(null, record),
			disabled: record.username == 'admin',
		},
		{
			title: '删除',
			ifShow: record.username !== 'admin',
			popConfirm: {
				title: '是否确认删除',
				confirm: handleDelete.bind(null, record),
			},
		},
	];
}

function handleCreate() {
	openModal(true, {
		isUpdate: false,
	});
}

const [registerDrawer, { openDrawer }] = useDrawer();
function handlePermission(record: Recordable) {
	openDrawer(true, { record });
}

function handleEdit(record: Recordable) {
	openModal(true, {
		record,
		isUpdate: true,
	});
}

function handleDelete(record: Recordable) {
	deleteRole(record.roleId).then(
		() => {
			createMessage.success('删除成功');
			reload();
			console.log(record);
		},
		err => {
			createMessage.error(err);
		},
	);
}

function handleSuccess() {
	createMessage.success('操作成功');
	reload();
}
</script>
<style lang="less" scoped>
.tree {
	width: 300px;
	border-right: 1px solid #ddd;
	line-height: 45px;
	margin: 0 30px 0 0;
	.tree-wrap {
		width: 290px;
		overflow: auto;
	}
}
</style>
